package myPack1;

import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;

public class ReadFrmXL {
	public static int xRow;
	public static int xCols;
	//@Test
	public static String[][] readData(String filePath, int sheetNum) throws Exception{
		//String filePath = "D:\\testData.xls";
		File file = new File(filePath);
		
		FileInputStream fIP = new FileInputStream(file);
		
		HSSFWorkbook wb = new HSSFWorkbook(fIP);
		HSSFSheet sheet = wb.getSheetAt(sheetNum);
		
		xRow = sheet.getLastRowNum() + 1;
		System.out.println("Rows are : " + xRow);
		
		xCols = sheet.getRow(0).getLastCellNum();
		System.out.println("Cols are : " + xCols);
		
		String[][] xData = new String[xRow][xCols];
		
		for(int r=0; r<xRow; r++){
			HSSFRow row = sheet.getRow(r);
			
			for(int c=0; c<xCols; c++){
				HSSFCell cell = row.getCell(c);
				
				String value = cellToString(cell);
				 xData[r][c] = value;
				 
				 // System.out.print(value); //Print data in console
	             // System.out.print("##");
			}
			 //System.out.println("@");
		}
		return xData;
		
	}

	public static String cellToString(HSSFCell cell) {
		
		Object result = null;
		 int type = cell.getCellType();
		 
		 switch(type){
		 
		 case HSSFCell.CELL_TYPE_BLANK:
			 result = "";
			 //System.out.println("Its a blank cell.");
			 break;
			 
		 case HSSFCell.CELL_TYPE_BOOLEAN:
			 result = cell.getBooleanCellValue();
			 //System.out.println(result);
			 break;
			 
		 case HSSFCell.CELL_TYPE_ERROR:
			 throw new RuntimeException("There is some error");
		 
		 case HSSFCell.CELL_TYPE_FORMULA:
			 throw new RuntimeException("Formula can not be handle");
			 
		 case HSSFCell.CELL_TYPE_NUMERIC:
			 result = cell.getNumericCellValue();
			 //System.out.println(result);
			 break;
			 
		 case HSSFCell.CELL_TYPE_STRING:
			 result = cell.getStringCellValue();
			 //System.out.println(result);
			 break;
			 
		 default:
			 System.out.println("Out of world.");
		 }
		
		return result.toString();
	}
}
